﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UL360Data;
using System.Configuration;
using System.Reflection;

namespace UL360SurveyService.Models
{
    public class Settings
    {
        //Values from app.settings
        //Indicates the interval for running the executiontimer
        public double ExecutionTimeSecondInterval { get; set; }
        //Indicates if mailing should occur at specific time of day
        public bool RunAtSpecificTime { get; set; }
        //Indicates at wich time of day to send mail if RunAtSpecificTime is set to true
        public DateTime TimeToRun { get; set; }
        //Indicates from wich date and time to start looking for unfinnished courses
        public DateTime DontLookForCoursesOlderThan { get; set; }

        //Indicates when execution timer was last run
        public DateTime LastExecutionTimerRun { get; set; }

        //Settings containing intervals for sending mail
        public int SendSurveyMailInterval { get; set; }
        public int SendReminderMailInterval { get; set; }
        public int LastAnswerDateInterval { get; set; }
        public int MailIntervalMultiplier { get; set; }
        public int TimeBetweenIntervalSettingsLoadingFromDb { get; set; }

        //Settings for mailtemplates
        public string SurveyMailTemplatePath { get; set; }
        public string SurveyReminderMailTemplatePath { get; set; }
        public string ExtSurveyMailTemplatePath { get; set; }
        public string ExtSurveyReminderMailTemplatePath { get; set; }
        public string ErrorReportMailTemplatePath { get; set; }

        //Setting for mailmessage
        public string FromAddress { get; set; }
        public string SurveyUrl { get; set; }

        //SMTP Settings
        public string SMTPHost { get; set; }
        public int SMTPPort { get; set; }
        public string SMTPUser { get; set; }
        public string SMTPPassword { get; set; }

        //Eventlog settings
        public string EventlogSource { get; set; }

        //Error reports receiver address
        public string ErrorReportsReceiver { get; set; }

        //Path were service executable is run from
        public string ExePath { get; set; }

        public Settings()
        {
            //Get ExecutionTimeSecondInterval from app.settings
            double executionTimeSecondInterval = 30;
            double.TryParse(ConfigurationManager.AppSettings["ExecutionTimerSecondInterval"], out executionTimeSecondInterval);
            ExecutionTimeSecondInterval = executionTimeSecondInterval;

            //Get RunAtSpecificTime from app.settings
            bool runAtSpecificTime = false;
            //If bool could not be parsed
            if (!bool.TryParse(ConfigurationManager.AppSettings["RunAtSpecificTime"], out runAtSpecificTime))
            {
                //Try parsing as int
                int nRunAtSpecificTime;
                //If could be parsed as int
                if (int.TryParse(ConfigurationManager.AppSettings["RunAtSpecificTime"], out nRunAtSpecificTime))
                {
                    //Set bool values from int values
                    if (nRunAtSpecificTime == 0)
                    {
                        runAtSpecificTime = false;
                    }
                    else if(nRunAtSpecificTime == 1)
                    {
                        runAtSpecificTime = true;
                    }
                }

            }
            RunAtSpecificTime = runAtSpecificTime;

            //Get TimeToRun from app.settings
            DateTime timeToRun;
            DateTime.TryParse(ConfigurationManager.AppSettings["TimeToRun"], out timeToRun);
            TimeToRun = timeToRun;

            //Get DontLookForCoursesOlderThan from app.settings
            DateTime dontLookForCoursesOlderThan;
            DateTime.TryParse(ConfigurationManager.AppSettings["DontLookForCoursesOlderThan"], out dontLookForCoursesOlderThan);
            DontLookForCoursesOlderThan = dontLookForCoursesOlderThan;

            //Get SurveyMailTemplatePath from app.settings
            SurveyMailTemplatePath = ConfigurationManager.AppSettings["SurveyMailTemplatePath"];

            //Get SurveyReminderMailTemplatePath from app.settings
            SurveyReminderMailTemplatePath = ConfigurationManager.AppSettings["SurveyReminderMailTemplatePath"];

            //Get ExtSurveyMailTemplatePath from app.settings
            ExtSurveyMailTemplatePath = ConfigurationManager.AppSettings["ExtSurveyMailTemplatePath"];

            //Get ExtSurveyReminderMailTemplatePath from app.settings
            ExtSurveyReminderMailTemplatePath = ConfigurationManager.AppSettings["ExtSurveyReminderMailTemplatePath"];

            //Get ErrorReportMailTemplatePath from app.settings
            ErrorReportMailTemplatePath = ConfigurationManager.AppSettings["ErrorReportMailTemplatePath"];

            //Get FromAddress from app.settings
            FromAddress = ConfigurationManager.AppSettings["FromAddress"];

            //Get SurveyUrl from app.settings
            SurveyUrl = ConfigurationManager.AppSettings["SurveyUrl"];

            //Smtp settings
            SMTPHost = ConfigurationManager.AppSettings["SMTPHost"];
            int smtpPort = 25;
            int.TryParse(ConfigurationManager.AppSettings["SMTPPort"], out smtpPort);
            SMTPPort = smtpPort;
            SMTPUser = ConfigurationManager.AppSettings["SMTPUser"];
            SMTPPassword = ConfigurationManager.AppSettings["SMTPPassword"];

            //Eventlogsettings
            EventlogSource = ConfigurationManager.AppSettings["EventlogSource"];

            //Multiply SendSurveyMailInterval and SendReminderMailInterval to get number of days to add
            int mailIntervalMultiplier = 7;
            int.TryParse(ConfigurationManager.AppSettings["MailIntervalMultiplier"], out mailIntervalMultiplier);
            MailIntervalMultiplier = mailIntervalMultiplier;

            //Loads the interval settings from database
            LoadIntervalsFromDb();

            //Get TimeBetweenIntervalSettingsLoadingFromDb from app.settings
            int timeBetweenIntervalSettingsLoadingFromDb = 120;
            int.TryParse(ConfigurationManager.AppSettings["TimeBetweenIntervalSettingsLoadingFromDb"], out timeBetweenIntervalSettingsLoadingFromDb);
            TimeBetweenIntervalSettingsLoadingFromDb = timeBetweenIntervalSettingsLoadingFromDb;

            //Get the path were the executable is running from
            ExePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString() + "\\";

            //Get the receiver for error reports
            ErrorReportsReceiver = ConfigurationManager.AppSettings["ErrorReportsReceiver"];
        }

        //Print all settings
        public override string ToString()
        {
            string returnString = "Loaded settings:\n";

            //If there are properties
            if (this.GetType().GetProperties() != null)
            {
                //Get all properties in array
                PropertyInfo[] properties = this.GetType().GetProperties();

                //If the array of properties contains elements
                if (properties.Length > 0)
                {
                    //Loop through properties
                    foreach (PropertyInfo property in properties)
                    {
                        //Return property name and value, also check that values is not empty or null
                        returnString += 
                            property.Name + 
                            ": " +
                            (property.GetValue(this) != null ? property.GetValue(this).ToString() : "") + 
                            "\n";
                    }
                }
            }

            return returnString;
        }

        public void LoadIntervalsFromDb()
        {
            //Get settings from database
            using (var db = new UL360Entities())
            {
                //Settings
                var settings = db.SurveyIntervalSettings.DefaultIfEmpty(null).First();

                //If settings were found
                if (settings != null)
                {
                    SendSurveyMailInterval = settings.SendSurveyMailInterval;
                    SendReminderMailInterval = settings.SendReminderMailInterval;
                    LastAnswerDateInterval = settings.LastAnswerInterval;
                }
                //If no settings were found set default values
                else
                {
                    SendSurveyMailInterval = 2;
                    SendReminderMailInterval = 2;
                    LastAnswerDateInterval = 2;
                }
            }
        }
    }
}
